package com.qi.demo01.Lock8;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zjq
 * @date 2020/3/31 19:53
 * <p>
 * ReentrantLock();是可重入锁
 */
//可重入锁 ，lock
public class ReentrantLock_lock {
    public static void main(String[] args) {
        TPhone tPhone = new TPhone();
        new Thread(() -> {
            tPhone.sms();
        }, "t1").start();
        new Thread(() -> {
            tPhone.sms();
        }, "t2").start();
    }
}

class TPhone {
    Lock lock = new ReentrantLock();

    public void sms() {
        lock.lock();//lock.lock();lock.unlock();
//        lock.lock();
        //lock必须配对，不然会死锁
        try {
            System.out.println(Thread.currentThread().getName() + "==》sms");
            call();//这里也有锁
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void call() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "==》call");
            System.out.println("**********************");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}